package com.zmwx.subject.domain.service.impl;

import com.alibaba.druid.support.spring.stat.SpringStatUtils;
import com.alibaba.fastjson.JSON;
import com.zmwx.subject.common.enums.IsDeletedFlagEnum;
import com.zmwx.subject.domain.convert.SubjectCategoryConverter;
import com.zmwx.subject.domain.convert.SubjectLabelConverter;
import com.zmwx.subject.domain.entity.SubjectLabelBO;
import com.zmwx.subject.domain.service.SubjectCategoryDomainService;
import com.zmwx.subject.domain.entity.SubjectCategoryBO;
import com.zmwx.subject.infra.basic.entity.SubjectCategory;
import com.zmwx.subject.infra.basic.entity.SubjectLabel;
import com.zmwx.subject.infra.basic.entity.SubjectMapping;
import com.zmwx.subject.infra.basic.service.SubjectCategoryService;


import com.zmwx.subject.infra.basic.service.SubjectLabelService;
import com.zmwx.subject.infra.basic.service.SubjectMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    SubjectLabelService subjectLabelService;

    @Resource
    SubjectMappingService subjectMappingService;
    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Override
    public void add(SubjectCategoryBO subjectCategorybo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategorybo);
        subjectCategoryService.insert(subjectCategory);
    }


    @Override
    public List<SubjectCategoryBO> queryPrimaryCategory(SubjectCategoryBO subjectCategorybo) {
       /* SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(1L);*/
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategorybo);
        List<SubjectCategory> boList = subjectCategoryService.queryPrimary(subjectCategory);
        List<SubjectCategoryBO> SubjectCategoryBOList = SubjectCategoryConverter.INSTANCE.convertToCategoryBoList(boList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryBOList.queryPrimaryCategroy:{}", JSON.toJSONString(SubjectCategoryBOList));
        }
        SubjectCategoryBOList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            log.info("***subjectCount:{}***", subjectCount);
            bo.setCount(subjectCount);
        });
        return SubjectCategoryBOList;
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategorybo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategorybo);
        List<SubjectCategory> SubjectCategoryList = subjectCategoryService.queryPrimary(subjectCategory);
        List<SubjectCategoryBO> SubjectCategoryBOList = SubjectCategoryConverter.INSTANCE
                .convertToCategoryBoList(SubjectCategoryList);

        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryBOList.queryPrimaryCategroy:{}", JSON.toJSONString(SubjectCategoryBOList));
        }
        return SubjectCategoryBOList;
    }

    @Override
    public boolean update(SubjectCategoryBO subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBo);
        int count = subjectCategoryService.update(subjectCategory);

        return count > 0;
    }

    @Override
    public List<SubjectCategoryBO> queryCategoryAndLable(SubjectCategoryBO subjectCategoryBo) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(subjectCategoryBo.getId());
        // 考虑缓存里面取
        subjectCategory.setIsDelete(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryPrimary(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("subjectCategorieList*******:{}", JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertToCategoryBoList(subjectCategoryList);
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(category), labelThreadPool)
        ).collect(Collectors.toList());
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        completableFutureList.forEach(future -> {
            try {
                Map<Long, List<SubjectLabelBO>> resultMap = future.get();
                if (!CollectionUtils.isEmpty(resultMap)) {
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        categoryBOList.forEach(categoryBO -> {
            if (!CollectionUtils.isEmpty(map.get(categoryBO.getId()))) {
                categoryBO.setLabelBOList(map.get(categoryBO.getId()));
            }
        });
        if (log.isInfoEnabled()) {
            log.info("*********LabelBOList:{}", JSON.toJSONString(categoryBOList));
        }
        //一次获取标签信息
        return categoryBOList;
    }

    private Map<Long, List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO category) {
        if (log.isInfoEnabled()) {
            log.info("getLabelBOList:{}", JSON.toJSONString(category));
        }
        Map<Long, List<SubjectLabelBO>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)) {
            return null;
        }
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        labelList.forEach(label -> {
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(label.getId());
            subjectLabelBO.setLabelName(label.getLabelName());
            subjectLabelBO.setCategoryId(label.getCategoryId());
            subjectLabelBO.setSortNum(label.getSortNum());
            labelBOList.add(subjectLabelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }
}
